package com.cloudeasy.post.service.expand;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.api.vo.post.SimpleUserInfoVO;
import com.cloudeasy.api.vo.user.UserInfoVO;
import com.cloudeasy.core.bean.JwtParser;
import com.cloudeasy.post.client.UserClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SimpleUserInfoService {
    private final JwtParser jwtParser;

    private final UserClient userClient;

    @Autowired
    public SimpleUserInfoService(JwtParser jwtParser, UserClient userClient) {
        this.jwtParser = jwtParser;
        this.userClient = userClient;
    }

    /**
     * 获取当前用户简单信息
     *
     * @param authentication {@link Authentication}
     * @return {@link SimpleUserInfoVO}
     */
    public SimpleUserInfoVO obtainSimpleUserInfo(Authentication authentication) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        String avatar = (String) jwtParser.getOnBody(authentication, "avatar");
        String nickname = (String) jwtParser.getOnBody(authentication, "nickname");

        return SimpleUserInfoVO.builder()
                .id(userId)
                .avatar(avatar)
                .nickname(nickname)
                .build();
    }

    /**
     * 获取简单用户信息
     *
     * @param userIds 用户Id列表
     * @return {@link List <SimpleUserInfoVO>}
     */
    public List<SimpleUserInfoVO> obtainSimpleUserInfo(List<String> userIds) {
        if (userIds == null || userIds.size() == 0) {
            return null;
        }
        Result<List<UserInfoVO>> result = userClient.list(userIds, null, null, null);
        if (!result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
            throw new CloudEasyException(Objects.requireNonNull(ResultCodeEnum.get(result.getCode())));
        }
        return result.getData().stream().map(userInfoVO -> {
            SimpleUserInfoVO simpleUserInfoVO = new SimpleUserInfoVO();
            BeanUtils.copyProperties(userInfoVO, simpleUserInfoVO);
            return simpleUserInfoVO;
        }).collect(Collectors.toList());
    }
}
